<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>系统管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-row :gutter="25">
               <el-col :span="4">
                  <el-input size="small" clearable placeholder="输入用户名" v-model="queryParams.name" /> 
              </el-col>
              <el-col :span="4">
                  <el-input size="small" clearable placeholder="输入角色code" v-model="queryParams.code" /> 
              </el-col>
               <el-col :span="2" >
                  <el-button size="small" type="success" @click="queryPage" icon="el-icon-search" v-if="permissionStrValue.indexOf('roleList:query') !== -1">查询</el-button>
              </el-col>
              <el-col :span="2" >
                  <el-button size="small" type="primary" @click="showAdd" icon="el-icon-plus" v-if="permissionStrValue.indexOf('roleList:add') !== -1">新增</el-button>
              </el-col>
            </el-row>
             <!--放表格-->
        <el-table :data="list" border >
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="角色编码">
                <template slot-scope="scope">
                    <span style="color:#67C23A" size="medium">{{ scope.row.code }}</span>
                </template>
            </el-table-column>
            <el-table-column label="角色名称">
                <template slot-scope="scope">
                    <span style="color:#67C23A" size="medium">{{ scope.row.name }}</span>
                </template>
            </el-table-column>
            <el-table-column label="创建时间">
                <template slot-scope="scope">
                    <span style="color:#67C23A" size="medium">{{ scope.row.createTime }}</span>
                </template>
            </el-table-column>

            <el-table-column label="操作" width="250px">
                 <template slot-scope="scope">
                     <el-button type="warning" size="small" @click="giveToPermission(scope.row.code, scope.row.name, scope.row.id)" icon="el-icon-edit" v-if="permissionStrValue.indexOf('roleList:givePermission') !== -1">分配权限</el-button>
                     <el-button type="danger" size="small" @click="removeById(scope.row.id)" icon="el-icon-delete" v-if="permissionStrValue.indexOf('roleList:delete') !== -1">删除</el-button>
                 </template>
            </el-table-column>
        </el-table>

        <!--分页-->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.currPage"
          :page-sizes="[10,20, 30, 40, 50]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>

        <el-dialog
       title="新增数据"
       :visible.sync="addFlag"
       width="25%"
       @close="clearForm()">
       <el-form :model="addParams" label-width="100px" ref="messageObj" label-position="left" :rules="messageObjRules">
         <el-form-item label="角色名称:" prop="name">
           <el-input v-model="addParams.name" size="small" ></el-input>
         </el-form-item>
       </el-form>
       <span slot="footer" class="dialog-footer">
          <el-button @click="addFlag = false">取 消</el-button>
          <el-button type="primary" @click="addData()">确 定</el-button>
       </span>
     </el-dialog>

      <el-dialog
       title="分配权限"
       :visible.sync="showPermission"
       width="50%">
       <el-form label-width="100px" label-position="left" :model="permissionInfo">
         <span>角色名称： <el-input style="width:180px" disabled v-model="permissionInfo.role" size="small"></el-input></span>
       <div style="margin: 20px 20px">
                <el-tree
                    :data="data"
                    show-checkbox
                    default-expand-all
                    :default-checked-keys="haveRoleIds"
                    node-key="id"
                    ref="tree"
                    highlight-current
                    :props="defaultProps"
                    @check="getChildrenKeys()">
                </el-tree>
                <br>
                <span slot="footer" class="dialog-footer">
          <el-button @click="showPermission = false">取 消</el-button>
          <el-button type="primary" @click="addPermissionToRole()">确 定</el-button>
       </span>
        </div>  
       
       </el-form>
     </el-dialog>
            
        </el-card>
    </div>
    
</template>

<script>
export default {
    name: 'RoleList',
    data() {
        return {
            queryParams: {
                name: '',
                code: '',
                currPage: 1,
                pageSize: 10
            },
            total: 0,
            list: [],
            addFlag: false,
            showPermission: false,
            addParams: {
                name: ''
            },
            messageObjRules: {
               name: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' }
               ],

            },
            permissionInfo: {
                role: ''
            },
            data: [],
            defaultProps: {
                children: 'children',
                label: 'name'
            },
            /* 获取选中节点的id */
            ids: [],
            roleId: '',
            haveRoleIds: [],
            permissionStrValue: ''

        }
    },
    created() {
        this.queryPage();
        //获取权限值
       this.permissionStrValue = JSON.parse(window.sessionStorage.getItem('permissionList')).toString();
    },
    methods: {
       async queryPage() {
            const {data: res} = await this.$http.post('/user/role/list-page',JSON.stringify(this.queryParams), {
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                }
            });
           console.log(res)
            if(res.success) {
                this.list = res.data;
                this.total = res.total;
            } else {
                this.$message.error(res.message);
            }

        },
        showAdd() {
            this.addFlag = true;
        },
        addData() {
            this.$refs.messageObj.validate(async valid => {
                if(valid) {
                    const {data: res} = await this.$http.post('/user/role/add-role?name=' + this.addParams.name)
                    if(res.success) {
                        this.$message.success("增加成功！");
                        this.addFlag = false;
                        this.clearForm();
                        this.queryPage();
                    } else{
                        this.$message.error(res.message);
                    }
                }
            })
        },
        handleSizeChange(newPageSize) {
            this.queryParams.pageSize = newPageSize;
            this.queryPage();
        },
        handleCurrentChange(newPage) {
            this.queryParams.currPage = newPage;
            this.queryPage();

        },
        clearForm() {
            this.addParams.name = '';
        },
        //分配权限
        giveToPermission(code, name, id) {
            this.permissionInfo.role = name + "(" + code + ")";
            this.listPermission();
            this.roleId = id;
            this.getPermissionIds(id);
            this.showPermission = true;
        },
        async removeById(id) {
            const confirmResult = await this.$confirm('是否删除该角色?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => {
                return err;
            });
             //当用户确认时，则返回值为字符串：confirm
            //取消时，返回字符串cancel
            if (confirmResult !== 'confirm'){
                return this.$message.info("已取消删除")
            }
            const{data: res} = await this.$http.delete('/user/role/remove-by-id/' + id);
            if(res.success) {
                this.$message.success("删除成功！");
                this.queryPage();
            } else {
                this.$message.error(res.message);
            }
            
        },
        async listPermission() {
            const{data : res} = await this.$http.get('/user/permission/get-permission-tree')
            //console.log(res.data.list)
            this.data = res.data.list
        },
        getCheckedNodes() {
            console.log(this.$refs.tree.getCheckedNodes());
        },
        getChildrenKeys() {
            this.ids = [];
            var arr = this.$refs.tree.getCheckedNodes();
            console.log(arr)
            var permissionIds = [];
            arr.forEach((value) => {
                permissionIds.push(value.id);
            });
            const set = new Set(permissionIds);
            permissionIds = [...set];
            this.ids = permissionIds;
            console.log(JSON.parse(JSON.stringify(this.ids)));
        },

        setCheckedKeys(list) {
            this.$refs.tree.setCheckedKeys(list);
        },

        async addPermissionToRole() {
            var fd = new FormData();
            fd.append("roleId", this.roleId);
            fd.append("permissionIds", this.ids);
            console.log(fd)
            const{data: res} = await this.$http.post("/user/role-permission/give-role-to-permissions", fd);
            if(res.success) {
                this.$message.success("分配成功！");
                this.queryPage();
                this.showPermission = false;
            } else {
                this.$message.error(res.message);
            }

        },
        //获取角色已拥有的权限ids
        async getPermissionIds(roleId) {
            const{data: res} = await this.$http.get("/user/role-permission/get-role-permission/" + roleId);
            console.log(res.data.ids)
            this.haveRoleIds = res.data.ids;
            this.ids = res.data.ids;
        }

    }
}
</script>